'use strict';
const { Op } = require('sequelize');
const dayjs = require('dayjs');

/**
 * 订单同步队列处理器
 * 处理政采云订单的拉取、解析和存储
 */
module.exports = {
  /**
   * 拉取并保存政采云订单
   * @param {Object} ctx - Egg.js上下文
   * @param {Object} data - 任务数据
   * @param {string} [data.startTime] - 开始时间
   * @param {string} [data.endTime] - 结束时间
   * @param {boolean} [data.forceSync] - 是否强制同步，忽略最后同步时间
   */
  async fetchAndSaveOrders(ctx, data) {
    const { logger, service } = ctx;
    const { zcyApi, order, redis, lock } = service;
    const { forceSync = false } = data;

    // 获取分布式锁，防止重复同步
    const lockKey = 'order_sync_lock';
    const lockAcquired = await lock.acquire(lockKey, 5 * 60 * 1000); // 5分钟锁超时
    if (!lockAcquired) {
      logger.warn('订单同步任务已在执行中，跳过本次任务');
      return { success: false, message: '任务已在执行中' };
    }

    try {
      // 确定同步时间范围
      let startTime = data.startTime;
      let endTime = data.endTime || dayjs().format('YYYY-MM-DD HH:mm:ss');

      // 如果没有指定开始时间且不是强制同步，则使用最后同步时间
      if (!startTime && !forceSync) {
        const lastSyncTime = await redis.get('last_order_sync_time');
        startTime = lastSyncTime || dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss');
      }

      logger.info(`开始同步政采云订单: ${startTime} 至 ${endTime}`);

      // 分页拉取订单
      let pageNum = 1;
      const pageSize = 100;
      let total = 0;
      let hasMore = true;
      const allOrders = [];

      while (hasMore) {
        try {
          // 调用政采云API获取订单
          const response = await zcyApi.fetchOrders({
            startTime,
            endTime,
            pageNum,
            pageSize
          });

          const { code, message, data: orderData } = response;
          if (code !== 0) {
            throw new Error(`政采云API调用失败: ${message}`);
          }

          const { list, totalCount } = orderData;
          total = totalCount;
          allOrders.push(...list);

          logger.info(`拉取订单第${pageNum}页，获取${list.length}条，累计${allOrders.length}/${total}条`);

          // 判断是否还有更多数据
          hasMore = pageNum * pageSize < totalCount;
          pageNum++;

          // 防止API调用过于频繁
          if (hasMore) {
            await new Promise(resolve => setTimeout(resolve, 1000));
          }
        } catch (error) {
          logger.error(`拉取订单第${pageNum}页失败:`, error);
          // 单页失败不中断整个同步任务，记录错误后继续
          ctx.service.errorLog.record('order_sync', `拉取订单失败: ${error.message}`, { pageNum, startTime, endTime });
          hasMore = false;
        }
      }

      if (allOrders.length === 0) {
        logger.info('未获取到新订单数据');
        return { success: true, total, newOrders: 0 };
      }

      // 批量处理订单
      const result = await order.batchProcessOrders(allOrders);

      // 更新最后同步时间
      await redis.set('last_order_sync_time', endTime);

      logger.info(`订单同步完成: 共处理${total}条，新增${result.created}条，更新${result.updated}条，失败${result.failed}条`);

      return {
        success: true,
        total,
        newOrders: result.created,
        updatedOrders: result.updated,
        failedOrders: result.failed
      };
    } catch (error) {
      logger.error('订单同步任务失败:', error);
      ctx.service.errorLog.record('order_sync', `同步任务失败: ${error.message}`, data);
      throw error;
    } finally {
      // 释放分布式锁
      await lock.release(lockKey);
    }
  }
};